<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\CarsModel;

class CarsDao extends BaseDao
{
    public static function get_cars_builder($params = []){
        $query = CarsModel::query();

        $query->when(checkIsHasField($params,'car_id'),function ($query)use ($params){
            $query->where('car_id',$params['car_id']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'project_id'),function ($query)use ($params){
            $query->where('project_id',$params['project_id']);
        });

        return $query;
    }

    /**
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function add_car(array $params = []){
        $query = self::get_cars_builder($params);
        if($query->exists()){
            $result = $query->increment('num',1);
        }else{
            $result = $query->create($params);
        }
        if($result === false){
            self::error('添加失败');
        }
        return $query->first()->toArray();
    }

    /**
     * @throws SysExceptions
     */
    public static function inc_dec_car(array $params)
    {
        if(!checkIsHasField($params,'car_id')){
            self::error('请选择购物车');
        }else if(!checkIsHasField($params,'type')){
            self::error('类型不正确');
        }
        $query = self::get_cars_builder($params);
        if(!$query->exists()){
            self::error('购物车商品不存在');
        }
        //inc
        if($params['type'] == 1){
            $result = $query->increment('num',1);
        }else{
            //dec
            $result = $query->decrement('num',1);
        }
        if($result === false){
            self::error('失败');
        }
        return $query->first()->toArray();
    }

    /**
     * @throws SysExceptions
     */
    public static function del_car(array $params)
    {
        if(!checkIsHasField($params,'car_id')){
            self::error('请选择购物车');
        }
        $query = self::get_cars_builder($params);
        if(!$query->exists()){
            self::error('购物车商品不存在');
        }
        if($query->delete() === false){
            self::error('删除失败');
        }
    }


    /**
     * @throws SysExceptions
     */
    public static function del_cars($params = []){
        if(!checkIsHasField($params,'cars_id')){
            self::error('请选择购物车');
        }
        $cars_id = explode(',',$params['cars_id']);
        if(count($cars_id) < 1){
            self::error('类型不正确');
        }
        if(self::get_cars_builder(['user_id'=>$params['user_id']])->whereIn('car_id',$cars_id)->delete() === false){
            self::error('移除购物车失败');
        }
    }

    public static function get_cars(array $array)
    {
        return self::get_cars_builder($array)->with(['goodsInfo'])->get();
    }
}
